<template>
  <div class="padding-l-20 padding-r-20 padding-t-20 h-100 table-page">
    <filter-bar>
      <div slot="left-bar">
        <a-space>
          <a-input allowClear class="_searchInput position-r" placeholder="任务名称" enter-button v-model="searchForm.taskName" />
          <my-tree-select
            class="orgSelect"
            ref="myTree"
            :tree-data="orgTree"
            :value="treeValue"
            placeholder="请选择所属组织"
            :replaceFields="replaceFields"
            @selectChange="selectChange"
          />
          <a-select style="width: 180px" v-model="searchForm.auditStatus" placeholder="状态">
            <a-select-option value="0"> 检测中 </a-select-option>
            <a-select-option value="1"> 已完成 </a-select-option>
            <a-select-option value="2"> 检测失败 </a-select-option>
          </a-select>
          <a-range-picker valueFormat="YYYY-MM-DD" v-model="searchForm.date" style="width: 250px">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
          <a-button
            class="nbcs-btn nbcs-btn-search"
            @click="
              page.currentPage = 1;
              getList(page, searchForm);
            "
            >查询
          </a-button>
          <a-button class="nbcs-btn nbcs-btn-common" @click="initSearch">重置 </a-button>
        </a-space>
      </div>
    </filter-bar>
    <interval-bg></interval-bg>
    <opt-bar>
      <div slot="left-bar">图文检测</div>
      <div slot="right-bar">
        <a-space>
          <a-popconfirm v-if="permission('sys:checkTask:batchDelete')" title="确定删除吗？" @confirm="batchDel">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button class="nbcs-btn-default">批量删除</a-button>
          </a-popconfirm>
          <a-button class="nbcs-btn-default" @click="exportData(searchForm)" v-if="permission('sys:checkTask:export')"> 导出 </a-button>
          <a-button class="nbcs-btn-main-bg" @click="upload(null, false, '1')" v-if="permission('sys:checkTask:upload')"> 上传 </a-button>
        </a-space>
      </div>
    </opt-bar>
    <div style="background: #f5faff; padding: 10px 0 10px 22px; margin-bottom: 8px" v-show="titleVisible">
      <img @click="closeShow" src="../../assets/img/cancel.png" alt="" style="position: absolute; right: 35px; top: 150px" />
      <div><a-icon type="exclamation-circle" theme="filled" style="color: #0147ff" /> 温馨提示:</div>
      <div style="margin-left: 1px">1、识别结果仅供参考，建议对检测结果进行复核。</div>
      <div style="margin-left: 1px">2、若检测文件过大，可能会影响检测效率，检测进度可在检测列表中进行查看，请耐心等待。(若只检测文本内容，建议使用文本检测功能)</div>
    </div>
    <a-table
      bordered
      ref="_table"
      :columns="columns"
      :data-source="list"
      :pagination="pageConfig"
      rowKey="id"
      :loading="loading"
      :scroll="{ x: 1000, y: tableHeight }"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="violationCount" slot-scope="text">{{ text ? text + '处' : '' }}</span>
      <span slot="auditFilePath" slot-scope="text">
        <img :src="text" height="40px" />
      </span>
      <span slot="auditStatus" slot-scope="text, record">
        <a-tag v-if="record.auditStatus == 1" class="tag-green"> 检测完成 </a-tag>
        <a-progress v-else-if="record.auditStatus == 0" :percent="record.auditProcess" />
        <a-tag v-else class="tag-red" @click="checkError('失败原因', record.errorMsg)"> 检测失败 </a-tag>
      </span>
      <template slot="auditReasonList" slot-scope="text">
        <a-tag v-for="(item, index) in text" :key="index" class="tag-red">{{ item }}</a-tag>
      </template>
      <span slot="action" class="operation" slot-scope="text, record">
        <a @click="detail(record.id, record.taskType)" v-if="record.auditStatus == 0 || record.taskType == 'ppt'">查看检测结果</a>
        <a-divider type="vertical" v-if="record.auditStatus == 0 || record.taskType == 'ppt'"/>
        <a @click="exportDocData(record.taskAllId, record.fileType)" v-if="record.auditStatus == 0 || record.taskType == 'pdf' ||  record.taskType == 'word' " :loading="exportLoading"> 下载标注文档 </a>
        <a-divider type="vertical"  v-if="record.auditStatus == 0 || record.taskType == 'pdf' ||  record.taskType == 'word' " :loading="exportLoading" />
        <a v-if="record.auditStatus != 0" @click="logExport(record.id, record.taskType)">下载检测报告</a>
        <a-divider type="vertical" v-if="record.auditStatus != 0" />
        <a @click="upload(record, true)" v-if="permission('sys:checkTask:update')">重命名</a>
        <a-divider type="vertical" />
        <a-popconfirm title="确定删除吗？" @confirm="del(record)" v-if="permission('sys:checkTask:delete')">
          <a-icon slot="icon" type="question-circle-o" style="color: red" />
          <a class="table-red-btn">删除</a>
        </a-popconfirm>
      </span>
    </a-table>
    <result-detail ref="resultDetail"></result-detail>
    <verify-upload ref="VerifyUpload" @getList="getList(page, searchForm)"></verify-upload>
  </div>
</template>

<script>
import moment from 'moment';
import FilterBar from '@/layouts/FilterBar.vue';
import OptBar from '@/layouts/OptBar';
import IntervalBg from '@/layouts/IntervalBg';
import { list, delRecord, exportRecord } from '@/services/verify';
import VerifyUpload from './VerifyUpload.vue';
import { getOrgByUser } from '../../services/org';
import { list2Tree } from '../../utils/common';
import myTreeSelect from '../components/myTreeSelect';
import { batchDelRecord, docExport, verifyExport } from '../../services/verify';
import {exportExcel, blobToJson, getCheckElapsedTime} from '../../utils/util';
import { checkError } from '@/utils/myAnt';
import ResultDetail from './components/ResultDetail.vue';

export default {
  name: 'ImageVerifyList',
  components: { FilterBar, ResultDetail, VerifyUpload, OptBar, IntervalBg, myTreeSelect },
  data() {
    return {
      msgVisible: false,
      titleVisible: true,
      exportLoading: false,
      selectedRowKeys: [],
      taskTypeMap: {
        text: '文本',
        image: '图片',
        video: '视频',
        audio: '音频',
        ppt: 'PPT',
        word: 'WORD',
        pdf: 'PDF'
      },
      open: false,
      open2: false,
      orgTree: [],
      treeValue: undefined,
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id'
      },
      tableHeight: 0,
      loading: false,
      searchForm: [],
      list: [],
      columns: [
        // { title: '序号', dataIndex: 'sortId' },
        {
          title: '任务名称',
          dataIndex: 'taskName',
          width: 250
        },
        {
          title: '字数',
          dataIndex: 'textCount',
          width: 100
        },
        { title: '文件类型', dataIndex: 'taskType', width: 100 },
        { title: '违规风险数', dataIndex: 'violationCount', width: 120, scopedSlots: { customRender: 'violationCount' } },
        {
          title: '送审时间',
          dataIndex: 'createTime',
          width: 180
        },
        {
          title: '检测完成时间',
          dataIndex: 'auditTimeStr',
          width: 180
        },
        {
          title: '检测耗时',
          dataIndex: 'elapsedTime',
          width: 180,
          align: 'center'
        },
        {
          title: '检测状态',
          width: 120,
          dataIndex: 'auditStatus',
          scopedSlots: { customRender: 'auditStatus' },
          align: 'center'
        },
        {
          title: '提交人',
          dataIndex: 'userName',
          width: 120
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 240,
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      pageConfig: {
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
        pageSizeOptions: ['20', '30', '50'],
        total: 0,
        current: 1,
        showTotal: total => {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (page, pageSize) => {
          this.page.currentPage = 1;
          this.page.pageSize = pageSize;
          this.getList(this.page, this.searchForm);
        },
        onChange: page => {
          this.page.currentPage = page;
          this.pageConfig.current = page;
          this.getList(this.page, this.searchForm);
        }
      },
      page: {
        currentPage: 1,
        pageSize: 20
      }
    };
  },
  computed: {},
  created() {
    this.getList(this.page);
    this.getOrgAll();
  },
  mounted() {
    this.tableHeight = document.querySelector('.table-page').clientHeight - 360;
  },
  methods: {
    checkError,
    showModal() {
      this.msgVisible = true;
    },
    closeShow() {
      this.titleVisible = false;
      this.tableHeight = document.querySelector('.table-page').clientHeight - 275;
    },
    handleOk() {
      this.msgVisible = false;
    },
    permission(name) {
      let permissions = this.$store.getters['account/permissions'];
      return permissions.filter(m => m.id == name || m.operation.indexOf(name) >= 0).length > 0;
    },
    initSearch() {
      this.searchForm = [];
      this.treeValue = undefined;
      this.getList(this.page);
    },
    onChange(date, dateString) {
      if (dateString !== undefined && dateString !== '') {
        console.log(dateString);
        this.searchForm.date = dateString;
      }
    },
    getOrgAll() {
      getOrgByUser({ isFilterSys: 1 }).then(res => {
        if (res.data.code === 0) {
          this.orgTree = list2Tree(res.data.data);
        }
      });
    },
    selectChange(value) {
      this.searchForm.organId = value;
      this.treeValue = value;
      this.page.page = 1;
    },
    getList(page, params) {
      if (params && params.date && params.date.length > 0) {
        params.date[1] = moment(params.date[1]).format('YYYY-MM-DD 23:59:59');
      }
      this.loading = true;
      list(
        Object.assign(
          {
            page: page.currentPage,
            pageSize: page.pageSize,
            taskType: 'bigFile'
          },
          params
        )
      ).then(res => {
        this.loading = false;
        const { data } = res.data;
        // 检测耗时
        data.list.forEach(item => {
          //计算耗时
          item.elapsedTime = getCheckElapsedTime(item.createTime, item.auditTime)
        });
        this.list = data.list;

        this.pageConfig.current = data.page;
        this.pageConfig.total = data.totalRow;
      });
    },

    del(obj) {
      delRecord({ id: obj.id }).then(res => {
        if (res.data.code === 0) {
          this.$message.success('删除成功');
          this.getList(this.page, this.searchForm);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    exportData(param) {
      this.loading = true;
      verifyExport(
        Object.assign(
          {
            taskType: 'bigFile',
            ids: this.selectedRowKeys
          },
          param
        )
      ).then(res => {
        this.loading = false;
        if (res.data.type == 'application/json') {
          blobToJson(res.data).then(res => {
            if (res.code == 401) {
              this.$message.warning('登录已失效，请重新登录');
              this.$router.replace({ path: '/login' });
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          exportExcel(res.data, '文档导出.xlsx', 'excel');
        }
      });
    },
    exportDocData(taskAllId, fileType) {
      this.exportLoading = true;
      docExport(
        Object.assign({
          taskAllId: taskAllId
        })
      ).then(res => {
        this.exportLoading = false;
        console.log(res);
        if (res.status === 200) {
          exportExcel(res.data, '文档检测.' + fileType);
        } else {
          this.$message.error('当前任务没有生成标注文档');
        }
      });
    },
    //添加/编辑
    upload(record, isRename, ruleId) {
      this.$refs['VerifyUpload'].changeForm(true, record, isRename, 'bigFile', ruleId);
    },
    detail(id, taskType) {
      this.$refs.resultDetail.changeForm(true, { id, taskType });
    },
    batchDel() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请选择需要删除的记录');
        return;
      }
      batchDelRecord({ ids: this.selectedRowKeys }).then(res => {
        if (res.data.code === 0) {
          this.$message.success('删除成功');
          this.getList(this.page);
        } else {
          console.log(res);
          this.$message.error(res.data.message);
        }
      });
      this.selectedRowKeys = [];
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    async logExport(id) {
      this.exportLoading = true;
      let res = await exportRecord({ id });
      this.exportLoading = false;
      if (res.data.type == 'application/json') {
        blobToJson(res.data).then(res => {
          if (res.code == 401) {
            this.$message.warning('登录已失效，请重新登录');
            this.$router.replace({ path: '/login' });
          } else {
            this.$message.error(res.message);
          }
        });
      } else {
        exportExcel(res.data, '检测报告.pdf');
      }
    }
  }
};
</script>

<style lang="less" scoped>
.select {
  width: 170px;
  /deep/ .ant-select-selection {
    width: 100%;
  }
}
._input {
  width: 180px;
}
.table-page {
  .ant-table-wrapper {
    max-height: calc(100% - 150px);
  }
}
.orgSelect {
  width: 170px;
}

.operation{
  a {
    white-space: nowrap;
  }
}
</style>
